package com.cskaoyan.controller;

import com.cskaoyan.bean.BaseRespVo;
import com.cskaoyan.bean.Storage;
import com.cskaoyan.bean.vo.FileUploadVo;
import com.cskaoyan.bean.vo.SystemAdminVO;
import com.cskaoyan.service.StorageService;
import com.cskaoyan.util.StorageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author xudengfeng
 * @date 2020/12/6 15:37
 * <p>
 * 文件上传
 */

@RestController
@RequestMapping("admin/storage")
public class AdminStorageController {

    @Autowired
    StorageService storageService;

    @Value("${file.path}")
    String filePath;

    @Value("${server.port}")
    String port;

    //单张图片上传 1、上传到服务器 2、保存文件信息到数据库
    @RequestMapping("create")
    public FileUploadVo upload(MultipartFile file) throws FileNotFoundException, UnknownHostException {
        Storage storage = StorageUtils.setStorageInfo(file);
        //classpath 文件夹根目录
        String path = ResourceUtils.getURL("classpath:").getPath();
        File webFile = new File(path + filePath, storage.getKey());
        //保存文件至服务器
        try {
            file.transferTo(webFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //插入storage表
        String hostAddress = InetAddress.getLocalHost().getHostAddress();
        storage.setUrl("http://" + hostAddress + ":" + port + "/upload/" + storage.getKey());
        storageService.savaFileInfo(storage);
        return FileUploadVo.ok(storage);
    }

    /**
     * 储存文件展示
     */
    @RequestMapping("list")
    public BaseRespVo storageList(Integer page, Integer limit, String key, String name, String sort, String order) {
        SystemAdminVO systemAdminVO = storageService.queryStorageList(page, limit, key, name, sort, order);
        return BaseRespVo.ok(systemAdminVO);
    }

    /**
     * 更新储存文件信息
     */
    @RequestMapping("update")
    public BaseRespVo storageUpdate(@RequestBody Storage storage) {
        storageService.updateStorage(storage);
        return BaseRespVo.ok(storage);
    }

    /**
     * 删除文件
     */
    @RequestMapping("delete")
    public BaseRespVo storageDelete(@RequestBody Storage storage) {
        storageService.deleteStorage(storage);
        return BaseRespVo.ok();
    }

}
